package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.ShoppingCarBean;
import com.project.mapper.IShopMapper;
import com.project.service.IShoppingCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Service
public class ShoppingCarImpl implements IShoppingCarService {
    @Autowired
    private IShopMapper mapper;
    @Override
    public List<ShoppingCarBean> findById(Integer userId) {

        return mapper.findCars(userId);
    }

    @Override
    public void addCar(Integer productId, Integer userId) {
        QueryWrapper<ShoppingCarBean> qw = new QueryWrapper<>();
        qw.eq("fK_userId",userId);
        qw.eq("fk_productId",productId);

        ShoppingCarBean shop = mapper.selectOne(qw);
        if (shop != null){//商品存在
            shop.setBuyNum(shop.getBuyNum()+1);
            mapper.updateById(shop);
        }
        else{
            shop = new ShoppingCarBean();
            shop.setProductId(productId);
            shop.setUserId(userId);
            shop.setBuyNum(1);
            mapper.insert(shop);
        }

    }

    @Override
    public void removeCar(Integer carId) {
        mapper.deleteById(carId);
    }

    @Override
    public void update(Integer carId, Integer num) {
        ShoppingCarBean shop = mapper.selectById(carId);
        shop.setBuyNum(num);
        mapper.updateById(shop);
    }
}
